# -*- coding: utf-8 -*-
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urlencode, datetime
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanGanzizangzuPolicy(BaseTaxPolicySpider):
    name = 'sichuan_ganzizangzu_policy'

    province = '四川省'
    city = '甘孜藏族自治州'
    # county = '滑县'
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
                'DEFAULT_REQUEST_HEADERS': {
                    'Accept': 'application/json, text/plain, */*',
                    'Accept-Language': 'zh,en;q=0.9,zh-CN;q=0.8',
                    'Content-Type': 'application/json'
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh,en;q=0.9,zh-CN;q=0.8',
        'cache-control': 'no-cache',
        'content-type': 'application/json',
        'origin': 'https://www.gzz.gov.cn',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://www.gzz.gov.cn/xzgfxwj',
        'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
    }

    def start_requests(self):
        for source, county, url in [
            ['甘孜藏族自治州炉霍县人民政府', "炉霍县", "http://www.luhuo.gov.cn/governmentInfo/zfxxgk/gfxwj"],
            ['甘孜藏族自治州甘孜县人民政府', "甘孜县", "http://www.ganzi.gov.cn/governmentInfo/zfxxgk/zcgfxwj"],
            ['甘孜藏族自治州色达县人民政府', "色达县", "http://www.gzzsdxrmzf.gov.cn/governmentInfo/sdx_zfxxgk/gfxwj"],
            ['甘孜藏族自治州德格县人民政府', "德格县", "http://www.dege.gov.cn/governmentInfo/zfxxgk/xzgfxwj"],
            ['甘孜藏族自治州德格县人民政府', "德格县", "http://www.dege.gov.cn/governmentInfo/zfxxgk/qtwj"],
            ['甘孜藏族自治州石渠县人民政府', "石渠县", "http://www.shiqu.gov.cn/governmentInfo/sqx_zfxxgk/gfxwj"],
            ['甘孜藏族自治州石渠县人力资源和社会保障局', "石渠县", "http://www.shiqu.gov.cn/governmentInfo/sqxrmzf_bm_sqxrlzyhshbzj/sqxrmzf_bm_sqxrlzyhshbzj_zcwj"],
            ['甘孜藏族自治州新龙县人民政府', "新龙县", "http://www.gzxl.gov.cn/governmentInfo/zfxxgk/xlxrmzfzfxxgkzcgfxwj"],
            ['甘孜藏族自治州理塘县人民政府', "理塘县", "http://www.gzlt.gov.cn/governmentInfo/ltx_zfxxgk/gfxwj"],
            ['甘孜藏族自治州巴塘县人民政府', "巴塘县", "http://www.batang.gov.cn/governmentInfo/btx_zfxxgk/old-gfxwj"],
            ['甘孜藏族自治州乡城县人民政府', "乡城县", "http://www.xcx.gov.cn/governmentInfo/xcx_zfxxgk/xzgfxwj"],
            ['甘孜藏族自治州稻城县人民政府', "稻城县", "http://www.daocheng.gov.cn/governmentInfo/dcx_zfxxgk/old-gfxwj"],
            ['甘孜藏族自治州得荣县人民政府', "得荣县", "http://www.gzdr.gov.cn/governmentInfo/drx_zfxxgk/old-gfxwj"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        path = response.url.split('/')[-1]
        meta = response.meta
        if path in response.text and 'changeMenu' in response.text:
            chanid = re.findall(r"changeMenu\((\d+),\s*'"+path, response.text)[0]
            # chanid = response.xpath("//*[contains(@click, '"+path+"') and contains(@click, 'changeMenu')]").re_first("changeMenu\((\d+),\s*'")
            print(response.url, chanid)
            data = {
                "columnId": chanid,
                "current": 1,
                "size": 50
            }
            meta['data'] = data
            data = json.dumps(data, separators=(',', ':'))
            yield scrapy.Request(response.urljoin('/site-service/c/esCManuscript/selectCListPage'), method='POST',
                                 callback=self.parse_list, body=data, meta=meta, headers=self.headers)
        else:
            print('ERROR', response.url)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        data = meta['data']
        prev_item = response.meta.get('item')
        json_datas = response.json()['data']
        elem_list = json_datas['records']
        for elem in elem_list:
            item = Item()
            item['source_url'] = f"/{elem['folder']}/article/{elem['manuscriptId']}"
            item['publish_date'] = elem['establishTime']
            item['title'] = elem['title']
            item['source_url'] = response.urljoin(item['source_url'])

            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(data, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = json_datas['pages']
            print(response.url, 'total', total_page, json_datas['total'])
            meta.update({'item': prev_item, 'is_next': False})
            for page_num in range(2, int(total_page) + 1):
                data['current'] = page_num
                body = json.dumps(data, separators=(',', ':'))
                yield scrapy.Request(response.url, method='POST',
                                     callback=self.parse_list, body=body, meta=meta, headers=self.headers)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get() or response.xpath("/title/text()").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").re_first(r"\d{4}-\d{2}-\d{2}")
        print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_ganzizangzu_policy".split())
